<template>
  <el-dialog
    :title="dialogTitle"
    v-model="addModuleVisible"
    width="50%"
    class="addModuleFlex"
  >
    <div class="m-center w-10/12">
      <el-form
        ref="moduleForm"
        :model="moduleForm"
        label-width="120px"
        :rules="addModuleRules"
      >
        <el-form-item
          :label="'Billing cycle'"
          prop="billingCycle"
          v-if="!isEdit"
        >
          <el-radio-group
            v-model="moduleForm.billingCycle"
            @change="changeBillingCycle"
          >
            <el-radio label="MONTH">{{
              $t('modules.contract.monthly')
            }}</el-radio>
            <!--              <el-radio label="QUARTER">{{$t('modules.contract.quarterly')}}</el-radio>-->
            <el-radio label="ANNUALLY">{{
              $t('modules.contract.annually')
            }}</el-radio>
            <el-radio label="ONCE">{{
              $t('modules.contract.one_time_charge')
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('modules.contract.plat')"
          prop="platCode"
          v-if="!isEdit"
        >
          <el-select
            v-model="moduleForm.platCode"
            size="small"
            clearable
            style="width: 100%"
            @focus="getPlatCode"
            @change="changePlateCode"
          >
            <el-option
              v-for="item in platOptions"
              :key="item.value"
              :label="$t('contract_plat.' + item.value)"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('modules.contract.billing_method')"
          prop="statisticMethodCode"
          v-if="!isEdit"
        >
          <el-select
            v-model="moduleForm.statisticMethodCode"
            clearable
            size="small"
            style="width: 100%"
            @change="changeStatisticMethod"
          >
            <el-option
              v-for="item in statisticOptions"
              :key="item.value"
              :label="$t('contract_statistic.' + item.value)"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('modules.contract.start_date')"
          v-if="
            moduleForm.billingCycle == 'ONCE' ||
            moduleForm.billingCycle == 'ANNUALLY'
          "
        >
          <template #label>
            {{ $t('modules.contract.start_date') }}
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('modules.contract.date_explain')"
              placement="top"
            >
              <svg-icon icon-class="explain" />
            </el-tooltip>
          </template>
          <el-date-picker
            v-model="moduleForm.billStartTime"
            style="width: 100%"
            :format="'YYYY-MM-DD'"
            :value-format="'timestamp'"
            size="small"
            type="date"
          />
        </el-form-item>
        <el-form-item
          id="priceInput"
          :label="
            this.moduleForm.billingCycle == 'ONCE' ||
            this.moduleForm.billingCycle == 'ANNUALLY'
              ? $t('modules.contract.price')
              : $t('modules.contract.unit_price')
          "
          prop="price"
        >
          <el-input v-model="moduleForm.price" size="small" style="width: 100%">
            <template #append>USD</template>
          </el-input>
        </el-form-item>
        <el-form-item
          v-if="currentStatisticOption && currentStatisticOption.allowFreeNum"
          prop="freeNum"
        >
          <template #label>
            <span>
              <div style="margin-bottom: -20px; display: inline-block">
                {{ $t('modules.contract.free_count') }}
                <el-tooltip placement="top">
                  <template #content>
                    <div>
                      {{ $t('modules.contract.free_count_explain') }}
                    </div></template
                  >
                  <i class="el-icon-warning" style="font-size: 2px" />
                </el-tooltip>
              </div>
            </span>
          </template>
          <!-- The quantity that can be free according to this billing method -->
          <el-input
            v-model="moduleForm.freeNum"
            size="small"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('common.remark')">
          <el-input
            v-model="moduleForm.remark"
            type="textarea"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="small" @click="addModuleVisible = false">{{
          $t('common.cancel')
        }}</el-button>
        <el-button
          v-permission="{ permission: '10401000.MANAGE' }"
          size="small"
          type="primary"
          @click="addModuleInfo"
          >{{ $t('common.confirm') }}</el-button
        >
      </span></template
    >
  </el-dialog>
</template>
<script>
import { findStaticMethod, findPlatCode } from '@/api/module'
export default {
  data() {
    var priceValidator = (rule, value, callback) => {
      var reg = new RegExp(/^[0-9]+(\.[0-9]{1,4})?$/)
      if (value && value !== '') {
        if (!reg.test(value)) {
          return callback(new Error('格式有误'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var freeCountValidator = (rule, value, callback) => {
      var reg = new RegExp(/^[0-9]+(\.[0-9]{1,2})?$/)
      if (value || value === 0) {
        if (!reg.test(value)) {
          return callback(new Error('格式有误'))
        } else {
          callback()
        }
      } else {
        callback(new Error())
      }
    }
    return {
      dialogTitle: '',
      platOptions: [],
      currentStatisticOption: {},
      statisticOptions: [],
      allowFreeNum: false,
      addModuleVisible: false,
      isEdit: false,
      moduleForm: {
        contractDetailUuid: '',
        platCode: '',
        moduleCode: '',
        statisticMethodCode: '',
        billingCycle: 'MONTH',
        billTarget: '',
        currency: 'USD',
        price: '',
        freeNum: 0,
        billStartTime: null,
        remark: ''
      },
      addModuleRules: {
        billingCycle: [
          {
            required: true,
            message: this.$t('common.module_require'),
            trigger: 'blur'
          }
        ],
        platCode: [
          {
            required: true,
            message: this.$t('common.platform_require'),
            trigger: 'blur'
          }
        ],
        statisticMethodCode: [
          {
            required: true,
            message: this.$t('common.statistic_require'),
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: this.$t('common.price_require'),
            trigger: 'blur'
          },
          {
            validator: priceValidator,
            message: this.$t('common.price_form_error')
          }
        ],
        freeNum: [
          {
            required: true,
            message: this.$t('common.free_count_require'),
            trigger: 'blur'
          },
          {
            validator: freeCountValidator,
            message: this.$t('common.free_count_error')
          }
        ]
      }
    }
  },
  methods: {
    // 获取platCode
    getPlatCode() {
      findPlatCode()
        .then((res) => {
          this.platOptions.length = 0
          for (let i = 0; i < res.length; i++) {
            const temp = {
              value: res[i].platCode,
              label: res[i].platCode
            }
            this.platOptions.push(temp)
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    addModuleInfo() {
      this.moduleForm.billTarget = this.currentStatisticOption.billTarget
      this.moduleForm.moduleCode = this.currentStatisticOption.moduleCode
      this.moduleForm.billStartTime = (
        this.moduleForm.billStartTime / 1000
      ).toFixed(0)
      if (this.isEdit) {
        delete this.moduleForm.creTime
        this.$confirm(this.$t('tip_content.edit_module'), '', {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        })
          .then(() => {
            this.$emit('editModule', this.moduleForm)
            this.addModuleVisible = false
          })
          .catch(() => {})
      } else {
        this.$emit('addModule', this.moduleForm)
        this.addModuleVisible = false
      }
    },
    changeBillingCycle() {
      if (this.moduleForm.platCode) {
        this.getStatisticMethodCode()
      }
      this.moduleForm.moduleCode = ''
      this.moduleForm.statisticMethodCode = ''
      this.currentStatisticOption = null
    },
    changePlateCode() {
      this.getStatisticMethodCode()
      this.moduleForm.moduleCode = ''
      this.moduleForm.statisticMethodCode = ''
      this.currentStatisticOption = null
    },
    getStatisticMethodCode() {
      const params = {
        billingCycle: this.moduleForm.billingCycle,
        platCode: this.moduleForm.platCode
      }
      findStaticMethod(params)
        .then((res) => {
          this.statisticOptions.length = 0
          for (let i = 0; i < res.length; i++) {
            const temp = {
              value: res[i].statisticMethodCode,
              label: res[i].statisticMethodName,
              moduleCode: res[i].moduleCode,
              allowFreeNum: res[i].allowFreeNum,
              billTarget: res[i].billTarget
            }
            if (
              res[i].statisticMethodCode === this.moduleForm.statisticMethodCode
            ) {
              this.currentStatisticOption = temp
            }
            this.statisticOptions.push(temp)
          }
          console.log(this.statisticOptions)
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    changeStatisticMethod(val) {
      this.currentStatisticOption = this.statisticOptions.filter(
        (item) => item.value === val
      )[0]
      console.log(this.moduleForm)
    },
    openDialog(moduleInfo, isEdit) {
      if (isEdit) {
        this.isEdit = isEdit
        this.dialogTitle = this.$t('modules.contract.edit_module')
        if (moduleInfo.billStartTime) {
          moduleInfo.billStartTime = new Date(moduleInfo.billStartTime * 1000)
        }
        this.moduleForm = { ...moduleInfo }
        this.$nextTick(() => {
          this.getStatisticMethodCode()
        })
      } else {
        this.isEdit = null
        this.dialogTitle = this.$t('modules.contract.add_module')
        this.moduleForm.platCode = ''
        this.moduleForm.moduleCode = ''
        this.moduleForm.statisticMethodCode = ''
        this.moduleForm.billingCycle = 'MONTH'
        this.moduleForm.billTarget = ''
        this.moduleForm.currency = 'USD'
        this.moduleForm.price = null
        this.moduleForm.freeNum = 0
        this.moduleForm.billStartTime = null
        this.moduleForm.remark = ''
      }
      this.addModuleVisible = true
    }
  }
}
</script>
<style  lang="scss" scoped>
</style>
